import { Result } from "@aspire/core";
import {
	ArgumentsHost,
	Catch,
	ExceptionFilter,
	HttpException,
	HttpStatus,
} from "@nestjs/common";
import { HttpAdapterHost } from "@nestjs/core";

@Catch(HttpException)
export class HttpExceptionFilter<T> implements ExceptionFilter {
	constructor(private adapterHost: HttpAdapterHost) {}

	catch(exception: T, host: ArgumentsHost) {
		const adapter = this.adapterHost.httpAdapter;

		const ctx = host.switchToHttp();
		const req = ctx.getRequest();
		const res = ctx.getResponse();

		const code =
			exception instanceof HttpException
				? exception.getStatus()
				: HttpStatus.INTERNAL_SERVER_ERROR;
		const errorException =
			exception instanceof HttpException
				? exception?.getResponse?.()
				: exception;

		// 定义错误格式
		const error = {
			success: false,
			errCode: code.toString(),
			msg:
				typeof errorException === "string"
					? errorException
					: // biome-ignore lint/suspicious/noExplicitAny: <explanation>
						(errorException as any)?.message || errorException,
			model: null,
		} satisfies Result<null>;
		console.error("【HTTP_EXCEPTION_FILTER】", exception);

		adapter.reply(res, error, code);
	}
}
